package logic

import (
	"context"
	"errors"
	"hippofresh/model/mysql"

	"hippofresh/hippofreshrpc/hippofreshrpc"
	"hippofresh/hippofreshrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HippoFreshAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHippoFreshAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HippoFreshAddLogic {
	return &HippoFreshAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HippoFreshAddLogic) HippoFreshAdd(in *hippofreshrpc.HippoFreshAddRequest) (*hippofreshrpc.HippoFreshAddResponse, error) {
	// todo: add your logic here and delete this line
	var hippofresh mysql.HippoFresh
	begin := mysql.DB.Begin()
	err := hippofresh.FindTitle(begin, in.Title)
	if err == nil {
		begin.Rollback()
		return nil, errors.New("已经存在同样商品")
	}
	var typer mysql.Typer
	err = typer.FindTyper(begin, in.Name)
	if err != nil {
		typer = mysql.Typer{
			Name: in.Name,
		}
		err = typer.TyperAdd(begin)
		if err != nil {
			begin.Rollback()
			return nil, errors.New("添加失败")
		}
	}
	data := mysql.HippoFresh{
		Title:   in.Title,
		Name:    in.Name,
		Price:   float64(in.Price),
		TyperId: int(typer.ID),
	}
	err = data.HippoFresh(begin)
	if err != nil {
		begin.Rollback()
		return nil, err
	}
	begin.Commit()
	return &hippofreshrpc.HippoFreshAddResponse{
		FreshId: int64(data.ID),
	}, nil
}
